from django.shortcuts import render

# Create your views here.
from django.views import View
from django import http
from django_redis import get_redis_connection

from users.auth import ali_real_name_id
from utils.views import LoginRequiredJSONMixin
from .models import User
from django.http import JsonResponse
from django.db import DatabaseError
from django.urls import reverse
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin

import re,json
# Create your views here.
# 用户注册
class Register(View):
    # def get(self,request):
    #     """给前端提供注册页面"""
    #     return render(request,'register.html')


    def post(self, request):
        """实现用户注册业务逻辑"""
        # 接收参数：表单参数

        json_dict = json.loads(request.body.decode())
        password = json_dict.get('password')
        mobile = json_dict.get('mobile')
        phonecode = json_dict.get('phonecode')


        # 校验参数：前后端的校验需要分开，避免恶意用户越过前端逻辑发请求，要保证后端的安全，前后端的校验逻辑相同
        # 判断参数是否齐全:all([列表])：会去校验列表中的元素是否为空，只要有一个为空，返回false
        if not all([mobile, phonecode, password]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[35789]\d{9}', mobile):
            return http.JsonResponse({'errno': '-1', 'errmsg': '手机号格式有误'})

        if not re.match(r'^[a-zA-Z0-9_]{8,20}', password):
            return http.JsonResponse({'errno': '-1', 'errmsg': '密码长度必须是8-20位字符(字母、数字、下划线)'})
        # # 判断两次密码是否一致
        # if password != password2:
        #     return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断短信验证码是否输入正确
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return http.JsonResponse( {'errror':'-1','errmsg': '短信验证码已失效'})
        if phonecode.lower()!= sms_code_server.decode().lower():
            return http.JsonResponse({'error':'-1','errmsg': '输入短信验证码有误'})


        # 保存注册数据
        user = User.objects.create_user(username=mobile,mobile=mobile, password=password)

        print(user)
        # 实现状态保持
        login(request, user)

        # 响应结果
        return http.JsonResponse({'errno':'0','errmsg':'注册成功'})



# 用户登录
class LoginView(View):
    """用户登录"""
    def post(self, request):
        """实现用户登录逻辑"""
        # 接收参数
        json_dict= json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')

        # 校验参数
        if not all([mobile, password]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号')
        # 认证用户:使用账号查询用户是否存在，如果用户存在，再校验密码是否正确
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            return JsonResponse({'errno':'-1','errmsg': '手机号或密码错误'})
        if not user.check_password(password):
            return JsonResponse({'error':'-1','errmsg':'手机号或者用户名错误'})
        # 状态保持
        login(request, user)
        # 响应结果
        return JsonResponse({'errno':'0','errmsg':'登录正常'})


    def delete(self,request):
        logout(request)
        return http.JsonResponse({'errno': '0', 'errmsg': '退出成功'})

    def get(self,request):
        user = request.user
        user_data = {'name':user.username,'user_id':user.id}

        if not user:
            return JsonResponse({'errno':'4101','errmsg':'未登录'})
        else:
            return JsonResponse({'errno':'0','errmsg':'已登录','data':user_data})



from utils.image_storage import storage


class UpdateAvatar(LoginRequiredJSONMixin,View):
    #上传用户头像
    def post(self,request):
        user = request.user
        img_file = request.FILES.get('avatar')
        if img_file is None:
            return http.JsonResponse({'errno':"-1",'errmsg':'没有内容'})
        # user.avatar = img_file
        # user.save()
        # getvalue 方法
        image_data = img_file.file.getvalue()
        try:
            file_name = storage(image_data)
            print(file_name)
            user.avatar = file_name
            print(user.avatar)
            user.save()
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno':'-1','errmsg':'上传失败'})
        url = 'http://q17gq831r.bkt.clouddn.com/'
        avatar_url = url+file_name

        data = {"avatar_url": avatar_url}
        print(data)
        return http.JsonResponse({"errno": "0", "errmsg": "头像上传成功", "data": data})


import json
import re
from django.middleware import http
from django.shortcuts import render
from django import http
from django.views import View
from users.models import User
import urllib.request
import ssl
from urllib.parse import quote
import string

class Personal_center(LoginRequiredJSONMixin,View):
    '''
    个人中心
    1.获取用户id
    2.根据用户id查询数据库
    3.将查询的结果返回
    '''
    #1.获取用户id
    def get(self, request):
        domain_url = "http://q17gq831r.bkt.clouddn.com/"
        print(domain_url)
        file_url = str(request.user.avatar)
        print(file_url)
        data = {
            "avatar_url": domain_url+file_url,
            "create_time": request.user.date_joined,
            "mobile": request.user.mobile,
            "name": request.user.username,
            "user_id": request.user.id
        }
        return http.JsonResponse({'data': data, "errmsg":"OK", "errno": "0"})




class user_name_amend(LoginRequiredJSONMixin,View):
    '''
    用户名修改
    1.获取用户id
    2.获取修改后的用户名
    3.判断用户名是否为空
    4.保存到数据库中
    5.返回结果
    '''
    def put(self, request):
        user = request.user
        name = json.loads(request.body.decode()).get('name')
        if not name:
            return http.JsonResponse({'errno': '1', 'errmsg':'用户名为空'})
        else:
            # 4.保存到数据库中
            user.username = name
            user.save()
            return http.JsonResponse({"errno": "0", "errmsg": "修改成功"})


class Approve(LoginRequiredJSONMixin,View):
    # 用户身份实名验证
    def post(self, request):
        user = request.user
        # 1.获取用户名
        user_name = json.loads(request.body.decode()).get('real_name')
        # 1.2.获取   id_card     real_name
        user_card = json.loads(request.body.decode()).get('id_card')

        # 2.判断用户名是否为空---这个正则代表数字，字母，汉字。---身份证18位
        if not (re.match(r'^[a-zA-Z0-9\u4e00-\u9fa5]+$', user_name)) and (
        re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                 user_card)):  # 3.保存到数据库并返回

            return http.JsonResponse({"errno": "4002", "errmsg": "认证信息保存失败"})

        elif not (re.match(r'^[a-zA-Z0-9\u4e00-\u9fa5]+$', user_name)) and (
        re.match(r'^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$', user_card)):
            return http.JsonResponse({"errno": "4002", "errmsg": "认证信息保存失败"})

        code, respMessage = ali_real_name_id(user_name, user_card)

        if code == "0000":
            user.id_card = user_card
            user.save()
            return http.JsonResponse({"errno": "0", "errmsg": "认证信息保存成功"})
        else:
            return http.JsonResponse({"errno": "4002", "errmsg": "认证信息保存失败"})


    def get(self, request):
        # 用户实名认证页面展示
        if request.user.id_card:
            data = {
                'real_name':request.user.username,
                'id_card':request.user.id_card
            }
            return JsonResponse({'errno':'0','data':data})
        else:
            return JsonResponse({'errmsg':'用户未认证'})































